"""A sample skeleton vehicle app."""

import json
import logging

from sdv.util.log import (  # type: ignore
    get_opentelemetry_log_factory,
    get_opentelemetry_log_format,
)
from sdv.vehicle_app import VehicleApp, subscribe_topic
from vehicle import Vehicle  # type: ignore
# Configure the VehicleApp logger with the necessary log config and level.
logging.setLogRecordFactory(get_opentelemetry_log_factory())
logging.basicConfig(format=get_opentelemetry_log_format())
logging.getLogger().setLevel("DEBUG")
logger = logging.getLogger(__name__)

GET_GLOVE_REQUEST_TOPIC = "glove/setGlove/request"
GET_GLOVE_RESPONSE_TOPIC = "glove/setGlove/response"


class GloveLightApp(VehicleApp):
    """
    Sample skeleton vehicle app.

    The skeleton subscribes to a getglove MQTT topic
    to listen for incoming requests to get
    the current vehicle speed and publishes it to
    a response topic.

    It also subcribes to the VehicleDataBroker
    directly for updates of the
    Vehicle.Speed signal and publishes this
    information via another specific MQTT topic
    """

    def __init__(self, vehicle_client: Vehicle):
        # SampleApp inherits from VehicleApp.
        super().__init__()
        self.Vehicle = vehicle_client

    async def on_start(self):
        """Run when the vehicle app starts"""
        logger.info("begin on start function")

    @subscribe_topic(GET_GLOVE_REQUEST_TOPIC)
    async def on_get_glove_request_received(self, data_str: str) -> None:
        """The subscribe_topic annotation is used to subscribe for incoming
        PubSub events, e.g. MQTT event for GET_GLOVE_REQUEST_TOPIC.
        """

        # Use the logger with the preferred log level (e.g. debug, info, error, etc)
        logger.debug(
            "PubSub event for the Topic: %s -> is received with the data: %s",
            GET_GLOVE_REQUEST_TOPIC,
            data_str,
        )

        # Getting current glove state from VehicleDataBroker using the DataPoint getter.
        data_glove = (await self.Vehicle.Cabin.Lights.IsGloveBoxOn.get()).value

        # received data status
        data = json.loads(data_str)
        status = data["status"]
        if status:
            message = "on"
        else:
            message = "off"
        # check if data_glove and status are equal
        if data_glove == status:
            await self.publish_mqtt_event(
                GET_GLOVE_RESPONSE_TOPIC,
                json.dumps(
                    {
                        "result": {
                            "status": 0,
                            "message": f"""glove box light state is {message}""",
                        },
                    }
                ),
            )
        else:
            await self.Vehicle.Cabin.Lights.IsGloveBoxOn.set(status)
            await self.publish_event(
                GET_GLOVE_RESPONSE_TOPIC,
                json.dumps(
                    {
                        "result": {
                            "status": 0,
                            "message":
                                f"""glove box light current state is {message}""",
                        },
                    }
                ),
            )

